import { menu } from '@/mock/menuTree.js'

const state = {
  // 必须在store里保存一份菜单，store里的值刷新会重置，在router.beforeEach里作为判断条件。
  menu: [],
  menuUrl: []
}
const whiteList = ['/login', "/404", "/index"]

const actions = {
  generateRoutes({ state }) {
    return new Promise((resolve, reject) => {
      // 请求后台路由数据
      setTimeout(() => {
        let res = menu.data
        let urllist = genMenuUrlArr(res)
        state.menu = res
        state.menuUrl = urllist.concat(whiteList)
        resolve(res)
      }, 500)
    })
  },
}

// 生成菜单url数组
const genMenuUrlArr = function (list, arr = []) {
  list.forEach(li => {
    if (li.url) {
      arr.push(li.url)
    }
    if (li.children && li.children.length) {
      genMenuUrlArr(li.children, arr)
    }
  })
  return arr
}

export default {
  namespaced: true,
  state,
  actions
}